package kz.kstu.shop.app.util.locator;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Filipp_Stankevich
 *         created: 26.07.11 21:07
 */
public abstract class AbstractServiceLocator implements ServiceLocator{

    private static Map<String, Object> serviceCache = new HashMap<String, Object>();

    public <T> T getService(String serviceName, Class<T> serviceInterface) {
        String serviceFullName = getServiceFullName(serviceName);
        T service;
        if (serviceCache.containsKey(serviceFullName)) {
            service = (T) serviceCache.get(serviceFullName);
        } else {
            service = createService(serviceFullName, serviceInterface);
        }
        return service;
    }

    protected <T> T createService(String serviceFullName, Class<T> serviceInterface) {
        InitialContext context = getInitialContext();
        T service;
        try {
            service = (T) PortableRemoteObject.narrow(context.lookup(serviceFullName), serviceInterface);
            serviceCache.put(serviceFullName, service);
        } catch (NamingException e) {
            //TODO: replace own exception
            throw new RuntimeException(e);
        }
        return service;
    }

    protected abstract String getServiceFullName(String serviceName);

    protected abstract InitialContext getInitialContext();

}
